﻿using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.UI;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.Share;
using ASPNETVN.PORTAL.Components.Configuration;

namespace ASPNETVN.PORTAL.Modules.GUIDE.Controls
{
    public partial class GuideAreaManager : AddEditItemControl
    {
        private void BuildTreeView()
        {
            tvCategory.Nodes.Clear();
            IList<Category> allCategories = Category.SelectCollectionAll(this.ModuleID);
            IList<Category> topCategories = allCategories.Where(x => x.ParentID == 0).OrderBy(x => x.Title).ToList();

            string treeString = string.Empty;
            TreeNode rootNode = new TreeNode("Lĩnh vực hướng dẫn", "0", "~/Images/Icons/Office/icon_group_open.gif");

            foreach (Category topCategory in topCategories)
            {
                TreeNode topNode = new TreeNode(topCategory.Title, topCategory.ID.ToString(), "~/Images/Icons/folder.gif");
                rootNode.ChildNodes.Add(topNode);

                IList<Category> childCategories = allCategories.Where(x => x.ParentID == topCategory.ID).OrderBy(x => x.Title).ToList();

                foreach (Category childCategory in childCategories)
                {
                    TreeNode childNode = new TreeNode(childCategory.Title, childCategory.ID.ToString(), "~/Images/Icons/item.gif");
                    topNode.ChildNodes.Add(childNode);
                }
            }
            tvCategory.Nodes.Add(rootNode);
            tvCategory.DataBind();
        }

        protected void tvCategory_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (tvCategory.SelectedValue != "0")
            {
                pnlDetailView.Visible = true;
                int categoryID = Convert.ToInt32(tvCategory.SelectedValue);
                Category category = Category.Load(categoryID);
                hfCategoryID.Value = category.ID.ToString();
                txtEditTitle.Text = category.Title;
                txtEditDescription.Text = category.Description;

                if (category.ParentID == 0)
                {
                    ddlEditCategory.Items.Clear();
                    ddlEditCategory.Items.Add(new ListItem("Lĩnh vực hướng dẫn", "0"));
                    divPermission.Visible = false;
                }
                else
                {
                    ddlEditCategory.DataSource = Category.SelectCollectionAll(this.ModuleID).Where(x => x.ParentID == 0);
                    ddlEditCategory.DataBind();
                    ddlEditCategory.SelectedValue = category.ParentID.ToString();

                    // Category Permission.
                    divPermission.Visible = true;
                    this.BindCategoryFunction(categoryID);
                }

                // Category Information View.
                lblCategory.Text = ddlEditCategory.SelectedItem.Text;
                lblTitle.Text = category.Title;
                lblDescription.Text = category.Description;


            }
            else
            {
                pnlDetailView.Visible = false;
            }
        }

        private void BuildAddCategory()
        {
            ddlAddCategory.Items.Clear();
            IList<Category> allCategories = Category.SelectCollectionAll(this.ModuleID);
            IList<Category> topCategories = allCategories.Where(x => x.ParentID == 0).OrderBy(x => x.Title).ToList();
            ddlAddCategory.Items.Add(new ListItem("Lĩnh vực hướng dẫn", "0"));
            foreach (Category topCategory in topCategories)
            {
                ddlAddCategory.Items.Add(new ListItem("» " + topCategory.Title, topCategory.ID.ToString()));
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                this.BuildTreeView();

                this.BuildAddCategory();


            }
        }

        private void BindCategoryFunction(int categoryID)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();
            PortalDataSet.ModuleRow mRow = ds.Module.FindByID(this.ModuleID);
            Guid moduleDefinitionID = mRow.ModuleDefinitionID;

            // Custom permission.
            rptCustomFunctions.DataSource = CategoryFunction.SelectBy_ModuleDefinitionID(moduleDefinitionID);
            rptCustomFunctions.DataBind();

            // All Permissions by ModuleID.
            DataTable dtPermissions = CategoryPermission.SelectBy_CategoryID(categoryID).Tables[0];

            // All Roles by PortalID.
            DataTable dtRoles = Role.SelectAllByPortalID(Global.PortalID).Tables[0];
            for (int i = 0; i < rptCustomFunctions.Items.Count; i++)
            {
                Label lblFunctionID = rptCustomFunctions.Items[i].FindControl("lblFunctionID") as Label;
                CheckBoxList chkRoles = rptCustomFunctions.Items[i].FindControl("chkRoles") as CheckBoxList;
                foreach (DataRow row in dtRoles.Rows)
                {
                    ListItem item = new ListItem();
                    item.Text = row["Name"].ToString();
                    item.Value = row["ID"].ToString();
                    if (dtPermissions.Select(string.Format("RoleID = {0} AND FunctionID = '{1}' AND CategoryID = '{2}'", item.Value, lblFunctionID.Text, categoryID)).Length > 0)
                    {
                        item.Selected = true;
                    }
                    // Administrators Role.
                    if (item.Value == "1")
                    {
                        item.Selected = true;
                        item.Enabled = false;
                    }
                    chkRoles.Items.Add(item);
                }
            }
        }

        protected void btnSaveEditCategory_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(hfCategoryID.Value);
            Category category = Category.Load(id);
            category.ParentID = Convert.ToInt32(ddlEditCategory.SelectedValue);
            category.Title = txtEditTitle.Text;
            category.Description = txtEditDescription.Text;
            category.Update();

            // Refresh TreeView.
            this.BuildTreeView();

            // Refresh DropDownList.
            this.BuildAddCategory();

            // Refresh Category Information View.
            lblCategory.Text = ddlEditCategory.SelectedItem.Text;
            lblTitle.Text = category.Title;
            lblDescription.Text = category.Description;
        }

        protected void btnSaveAddCategory_Click(object sender, EventArgs e)
        {
            Category category = new Category();
            category.ModuleID = this.ModuleID;
            category.Title = txtAddTitle.Text;
            category.ParentID = Convert.ToInt32(ddlAddCategory.SelectedValue);
            category.Description = txtAddDescription.Text;
            category.Insert();

            // Reset controls.
            txtAddTitle.Text = txtAddDescription.Text = string.Empty;
            ddlAddCategory.SelectedIndex = 0;

            // Refresh TreeView.
            this.BuildTreeView();

            // Refresh DropDownList.
            this.BuildAddCategory();
        }

        protected void btnDeleteCategory_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(hfCategoryID.Value);
            Category.DeleteCategory(id);

            // Refresh TreeView.
            this.BuildTreeView();

            // Refresh DropDownList.
            this.BuildAddCategory();

        }

        protected void btnSavePermission_Click(object sender, EventArgs e)
        {
            // Update Category Permissions.
            int id = Convert.ToInt32(hfCategoryID.Value);
            for (int i = 0; i < rptCustomFunctions.Items.Count; i++)
            {
                Label lblFunctionID = rptCustomFunctions.Items[i].FindControl("lblFunctionID") as Label;
                CheckBoxList chkRoles = rptCustomFunctions.Items[i].FindControl("chkRoles") as CheckBoxList;
                ArrayList selectedRoles = new ArrayList();
                foreach (ListItem item in chkRoles.Items)
                {
                    if (item.Selected)
                    {
                        selectedRoles.Add(item.Value);
                    }
                }

                string[] roles = selectedRoles.ToArray(typeof(string)) as string[];
                CategoryPermission.UpdatePermissions(lblFunctionID.Text, id, roles);
            }

            // Alert.
            this.ShowMessage("Thông báo", "Lưu thông tin thành công!");
        }
    }
}